import type { PageResult, PageParams, BaseResponse } from '@/types/api.d'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

/**
 * 住院信息类型定义
 */
export interface Hospitalization {
  id: number
  admissionNo: string
  patientId: number
  patientName: string
  doctorId: number
  deptId: number
  admissionDate: string
  dischargeDate?: string
  hospitalId: number
  status: 'IN' | 'OUT' | 'TRANSFER'
  delFlag: 'Y' | 'N'
  createTime: string
  updateTime: string
}

/**
 * 住院查询参数
 */
export interface HospitalizationSearchParams extends PageParams {
  admissionNo?: string
  patientName?: string
  doctorId?: number
  deptId?: number
  hospitalId?: number
  status?: 'IN' | 'OUT' | 'TRANSFER'
  delFlag?: 'Y' | 'N'
}

/**
 * 获取住院列表
 * @param params 查询参数
 * @returns 分页结果
 */
export const fetchHospitalizations = async (params: HospitalizationSearchParams): Promise<PageResult<Hospitalization>> => {
  try {
    const { data } = await request.get<BaseResponse<PageResult<Hospitalization>>>('/api/hospitalizations', { params })
    return data.data
  } catch (error) {
    ElMessage.error('获取住院列表失败')
    throw error
  }
}

/**
 * 获取住院详情
 * @param id 住院ID
 * @returns 住院详情
 */
export const getHospitalization = async (id: number): Promise<Hospitalization> => {
  try {
    const { data } = await request.get<BaseResponse<Hospitalization>>(`/api/hospitalizations/${id}`)
    return data.data
  } catch (error) {
    ElMessage.error('获取住院详情失败')
    throw error
  }
}

/**
 * 创建住院记录
 * @param data 住院数据
 * @returns 创建的住院信息
 */
export const createHospitalization = async (data: Omit<Hospitalization, 'id'>): Promise<Hospitalization> => {
  try {
    const { data: response } = await request.post<BaseResponse<Hospitalization>>('/api/hospitalizations', data)
    ElMessage.success('创建住院记录成功')
    return response.data
  } catch (error) {
    ElMessage.error('创建住院记录失败')
    throw error
  }
}

/**
 * 更新住院记录
 * @param data 住院数据
 * @returns 更新后的住院信息
 */
export const updateHospitalization = async (data: Hospitalization): Promise<Hospitalization> => {
  try {
    const { data: response } = await request.put<BaseResponse<Hospitalization>>(`/api/hospitalizations/${data.id}`, data)
    ElMessage.success('更新住院记录成功')
    return response.data
  } catch (error) {
    ElMessage.error('更新住院记录失败')
    throw error
  }
}

/**
 * 删除住院记录
 * @param id 住院ID
 */
export const deleteHospitalization = async (id: number): Promise<void> => {
  try {
    await request.delete(`/api/hospitalizations/${id}`)
    ElMessage.success('删除住院记录成功')
  } catch (error) {
    ElMessage.error('删除住院记录失败')
    throw error
  }
}

/**
 * 办理出院
 * @param id 住院ID
 */
export const dischargePatient = async (id: number): Promise<void> => {
  try {
    await request.patch(`/api/hospitalizations/${id}/discharge`)
    ElMessage.success('出院办理成功')
  } catch (error) {
    ElMessage.error('出院办理失败')
    throw error
  }
}

// 缓存最近请求的住院数据
const hospitalizationCache = new Map<number, Hospitalization>()

/**
 * 获取住院详情（带缓存）
 * @param id 住院ID
 * @param forceRefresh 是否强制刷新缓存
 * @returns 住院详情
 */
export const getHospitalizationWithCache = async (id: number, forceRefresh = false): Promise<Hospitalization> => {
  if (!forceRefresh && hospitalizationCache.has(id)) {
    return hospitalizationCache.get(id)!
  }

  const hospitalization = await getHospitalization(id)
  hospitalizationCache.set(id, hospitalization)
  return hospitalization
}
